package com.cmict.data.form.api.service.impl;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 读取excel文件
 *
 * @author liutao
 * @date 2022/12/13
 */
@Slf4j
public class ImportExcelListener<T> extends AnalysisEventListener<T> {

    /**
     * 解析成功的数据
     */
    List<T> importList = new ArrayList<>();

    List<Map<Integer, String>> headMap = Lists.newArrayList();
    /**
     * 正文起始行
     */
    private Integer headRowNumber;
    /**
     * 合并单元格
     */
    private List<CellExtra> extraMergeInfoList = new ArrayList<>();

    public ImportExcelListener(Integer headRowNumber) {
        this.headRowNumber = headRowNumber;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param context context
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
//        log.info("解析到一条数据: {}", JSON.toJSONString(data));
        // 获取Excel行号(从0开始)
        ReadRowHolder readRowHolder = context.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        try {
            BeanUtils.setProperty(data, "lineNo", rowIndex + 1);
        } catch (IllegalAccessException e) {
            log.error("ImportExcelListener.invoke 设置行号异常: ", e);
        } catch (InvocationTargetException e) {
            log.error("ImportExcelListener.invoke 设置行号异常: ", e);
        }
        importList.add(data);
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap.add(headMap);
        log.info("head:{}", headMap);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
    }

    /**
     * 返回解析出来的List
     */
    public List<T> getData() {
        return importList;
    }

    /**
     * 读取额外信息：合并单元格
     */
    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        switch (extra.getType()) {
            case MERGE: {
                if (extra.getRowIndex() >= headRowNumber) {
                    extraMergeInfoList.add(extra);
                }
                break;
            }
            default:
        }
    }

    /**
     * 返回解析出来的合并单元格List
     */
    public List<CellExtra> getExtraMergeInfoList() {
        return extraMergeInfoList;
    }


    /**
     * 在转换异常，获取其他异常的情况下会调用此接口，
     * 抛出异常就停止读取，如果不抛出异常就继续读取。
     *
     * @paramexception
     * @paramcontext
     * @throwsException
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.info("解析失败，但是继续解析下一行：{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException e = (ExcelDataConvertException) exception;
            log.info("数据解析异常，所在行：{}，所在列：{}，数据是:{}", e.getRowIndex(), e.getColumnIndex(), e.getCellData());
        }
    }

}
